const http = require("http");
const fs = require("fs");

var userList = [];

function getData(str){
    var arr = str.split("&");
    var obj = {};
    for(var i=0;i<arr.length;i++){
        var childArr = arr[i].split("=");
        obj[childArr[0]] = childArr[1];
    }
    return obj;
}

http.createServer((req,res)=>{
    var urlObj = new URL(req.url,"http://localhost:8081/");
    var pathName = urlObj.pathname;
    if(pathName == '/'){
        var fileContent = fs.readFileSync("./post.html");
        res.writeHead(200,{"Content-Type":"text/html;charset=utf8"})
        res.write(fileContent);
        res.end();
    }
    //响应list.html到页面浏览器
    else if(pathName == '/list'){
        var fileContent = fs.readFileSync("./list.html");
        res.writeHead(200,{"Content-Type":"text/html;charset=utf8"})
        res.write(fileContent);
        res.end();
    }
    //做表单数据的接收，存储到了userList里
    else if(pathName == '/save'){
        var str = "";
        req.on("data",(chunk)=>{
            str += chunk;
        })
        req.on("end",()=>{
            var postObj = getData(str);
            console.log(postObj);
            userList.push(postObj);
            res.end("submit success");
        })
    }
    //响应userList数据到客户端
    else if(pathName == '/getlist'){
        var userStr = JSON.stringify(userList);
        res.writeHead(200,{"Content-Type":"text/plain"});
        res.end(userStr);
    }
    //删除数据的过程，接收请求/del?deluser=zhangsan
    //根据username从userList里面将数据删除
    else if(pathName == '/del'){
        var delUser = urlObj.searchParams.get("deluser");
        for(var i=0;i<userList.length;i++){
            if(userList[i]["username"]==delUser){
                userList.splice(i,1);
                res.end("delete success");
                return;
            }
        }
    }
}).listen(8081);